package com.motorola.dp.jenkinsmonitor.service.util.properties;

import static org.apache.commons.io.IOUtils.closeQuietly;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;

import com.motorola.dp.jenkinsmonitor.model.util.exception.PropertyReadException;

public class ClasspathPropertiesService extends DefaultPropertiesService {

    public ClasspathPropertiesService(String classpathResourceName) {
        setProperties(readPropsFromClasspath(classpathResourceName));
    }

    public static Properties readPropsFromClasspath(String resourceName) {
        Properties props = new Properties();

        URL cpResource = Thread.currentThread().getContextClassLoader().getResource(resourceName);
        if (cpResource != null) {
            InputStream is = null;
            try {
                is = cpResource.openStream();
                props.load(is);
                return props;
            } catch (IOException e) {
                throw new PropertyReadException("Could not read " + resourceName, e);
            } finally {
                closeQuietly(is);
            }
        }
        throw new PropertyReadException("Could not locate " + resourceName);
    }

}
